#!/usr/bin/env python
# -*- coding:utf-8 -*-
# getTimetable.pyで生成したsqlite DBファイルより情報を取得
#
# installing BeautifulSoup:
#        http://www.crummy.com/software/BeautifulSoup/
#        check python ver and get 3.0xxx or 3.1xxx, and python setup.py install
import codecs
import locale
import optparse
import sys
import EkikaraDb
import getTimetableLog


class Putter:
    def __init__(self, outputEncode, outputNewline):
        u"""

        default is to stdout.
        """
        self.filename = None
        self.outputEncode = outputEncode
        self.outputNewline = outputNewline
        self.fout = codecs.getwriter(outputEncode)(sys.stdout)
        if sys.platform == "win32":
            import os
            import msvcrt
            # stdoutをbinmodeに(U*nix系は元々binmode)
            msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

    def open(self, filename):
        self.filename = filename
        self.fout = codecs.open(self.filename, "wb", self.outputEncode)

    def writeln(self, s):
        u"""改行する
        """
        self.fout.write(s + self.outputNewline)  # encode()はオープン時に指定しているので不要

    def write(self, s):
        u"""改行しない
        """
        self.fout.write(s)  # encode()はオープン時に指定しているので不要

    def newLine(self):
        u"""改行のみ
        """
        self.fout.write(self.outputNewline)

    def close(self):
        u"""stdoutをクローズしちゃうとアレなのでファイルの時だけクローズする。
        """
        if self.filename:
            try:
                self.fout.close()
            finally:
                pass

    def __del__(self):
        self.close()


def main():
    logger = getTimetableLog.logging.getLogger("gettimetable")
    # parse command line
    optParser = optparse.OptionParser(usage="%prog -d DBFILE [options]", version="%prog 0.2")
    optParser.add_option("-d", "--db-file",
                         dest="dbFile",
                         help="use sqlite db file. less then use :memory:",
                         metavar="FILE")
    optParser.add_option("-e", "--output-encode",
                         dest="outputEncode",
                         help="write file or stdout charactor ENCODE. default is utf-8",
                         metavar="ENCODE")
    optParser.add_option("-f", "--output-file",
                         dest="outputFile",
                         help="listing write to FILE. over-write non confirm",
                         metavar="FILE")
    optParser.add_option("-i", "--timetable-id",
                         type="int",
                         dest="timetableId",
                         default=0,
                         help="specify TIMETABLE_ID for --station-list",
                         metavar="TIMETABLE_ID")
    optParser.add_option("-n", "--output-newline",
                         dest="outputNewline",
                         help="specify NEWLINE. default is \\n (if you for MS-Windows, \\r\\n)",
                         metavar="NEWLINE")
    optParser.add_option("-t", "--timetable-list",
                         action="store_true",
                         dest="timetableList",
                         help="print timetable list only. For --output-only.")
    optParser.add_option("-s", "--station-list",
                         action="store_true",
                         dest="stationList",
                         help="station list. formatting for --specify-station-list in setDiaData.py")
    (OPTIONS, args) = optParser.parse_args()
    if OPTIONS.dbFile:
        db = EkikaraDb.EkikaraDb(logger=logger, filename=OPTIONS.dbFile)
    else:
        optParser.error("specify --db-file=FILE")
        sys.exit(1)
    if OPTIONS.outputFile:
        # ファイル指定があるときのデフォルトはCP932 \r\n
        if OPTIONS.outputEncode == None:
            OPTIONS.outputEncode = 'CP932'
        if OPTIONS.outputNewline == None or OPTIONS.outputNewline == "\\r\\n":
            OPTIONS.outputNewline = "\r\n"
        else:
            OPTIONS.outputNewline = "\n"
        putter = Putter(OPTIONS.outputEncode, OPTIONS.outputNewline)
        putter.open(OPTIONS.outputFile)
    else:
        # ファイル指定が無いときのデフォルトはその環境のデフォルト
        if OPTIONS.outputEncode == None:
            OPTIONS.outputEncode = locale.getpreferredencoding()
        if OPTIONS.outputNewline:
            if OPTIONS.outputNewline == "\\r\\n":
                OPTIONS.outputNewline = "\r\n"
            else:
                OPTIONS.outputNewline = "\n"
        else:
            if sys.platform == "win32":
                OPTIONS.outputNewline = "\r\n"
            else:
                OPTIONS.outputNewline = "\n"
        putter = Putter(OPTIONS.outputEncode, OPTIONS.outputNewline)
    if OPTIONS.timetableList:
        putter.writeln(u"[imetable_id][company][line][updown(direction)][day]")
        for row in db.timetableList():
            if row:
                if row['direction'] and len(row['direction']) > 0:
                    updown = u"%s(%s)" % (row['updown'], row['direction'])
                else:
                    updown = row['updown']
                putter.writeln(u"[%d][%s][%s][%s][%s]" % (row['timetable_id'],
                                                      row['company'],
                                                      row['railway_line'],
                                                      updown,
                                                      row['day'],
                                                      ))
        sys.exit(0)  # normal exit.
    if OPTIONS.stationList:
        timetable = EkikaraDb.Timetable(db=db,
                                        target_timetable_id=OPTIONS.timetableId,
                                        logger=logger)
        attr = timetable.getAttr()
        fmtStr = u"%s\t%s\td"
        if attr['updown'] == 'up':
            fmtStr = u"%s\td\t%s"
        for row in db.lineStationList(timetable.getId()):
            # 着発時刻両方共表示しない場合でも発時刻は表示するので
            ad = u"d"
            if row['display_arrival'] == 1:
                ad = u"a" + ad
            putter.writeln(fmtStr % (row['station_name'], ad))
        sys.exit(0)


#--------- main
if __name__ == '__main__':
    main()
